package com.mybatis.mybatisdatab.config;

import com.mybatis.mybatisdatab.mapper.UserMapper;
import com.mybatis.mybatisdatab.pojo.User;
import org.apache.commons.collections.map.HashedMap;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.apache.shiro.session.Session;

import java.util.*;

public class UserRealm extends AuthorizingRealm {

    @Autowired
    private UserMapper userMapper;
    @Override
    //授权
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("执行了 doGetAuthorizationInfo 进入角色授权");

        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.addStringPermission("user:add");
        //拿到当前登录的这个用户
        Subject subject = SecurityUtils.getSubject();
        User currentUser = (User) subject.getPrincipal();//拿到User对象
        //设置当前用户的权限
        info.addStringPermission(currentUser.getPerms());

        return info;
    }

    @Override
    //认证
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        System.out.println("执行了 doGetAuthenticationInfo 进入用户登录");

        //用户名，密码 数据中取
        UsernamePasswordToken userToken = (UsernamePasswordToken) token;

        List<User> list = userMapper.queryUserByName(userToken.getUsername());
        User user = list.get(0);
        if (!userToken.getUsername().equals(user.getName())){
            return null;//抛出异常 UnknownAccountException
        }


        Subject currentSubject = SecurityUtils.getSubject();
        Session session = (Session) currentSubject.getSession();
        session.setAttribute("loginUser", user);
        //密码认证，Shiro做
        //传入转换后的盐
        return new SimpleAuthenticationInfo(user,user.getPwd(), user.getName());
    }
}
